package com.xiaoshuidi.cloud.module.system.controller.admin.oss.config;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.S3ClientOptions;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;

@Data
@Slf4j
@RefreshScope
@ConfigurationProperties(prefix = "oos.config")
public class OosClientConfig {
    private String accessKey;
    private String secretKey;
    private String endpoint;
    private String bucket;

    private String httpType;
    private String subUrl;

    public AmazonS3 oosClient() {
        ClientConfiguration clientConfig = new ClientConfiguration();
        // 设置连接的超时时间，单位毫秒
        clientConfig.setConnectionTimeout(30 * 1000);
        // 设置 socket 超时时间，单位毫秒
        clientConfig.setSocketTimeout(30 * 1000);
        if ("http".equals(httpType)){
            clientConfig.setProtocol(Protocol.HTTP); //设置 http
        }else {
            clientConfig.setProtocol(Protocol.HTTPS);
        }
        // 设置 V4 签名算法中负载是否参与签名，关于签名部分请参看《OOS 开发者文档》
        S3ClientOptions options = new S3ClientOptions();
        options.setPayloadSigningEnabled(true);
        // 创建 client
        AmazonS3 oosClient = new AmazonS3Client(
                new PropertiesCredentials(accessKey, secretKey), clientConfig);
        // 设置 endpoint
        oosClient.setEndpoint(endpoint);
        //设置选项
        oosClient.setS3ClientOptions(options);
        return oosClient;
    }
}
